package com.gulimall.gulimallorder.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.gulimall.common.enume.OrderStatusEnum;
import com.gulimall.common.utils.R;
import com.gulimall.common.vo.MemberEntityVo;
import com.gulimall.gulimallorder.constant.OrderConstant;
import com.gulimall.gulimallorder.dao.OrderItemDao;
import com.gulimall.gulimallorder.entity.OrderItemEntity;
import com.gulimall.gulimallorder.feign.CartFeignService;
import com.gulimall.gulimallorder.feign.MemberFeignService;
import com.gulimall.gulimallorder.feign.ProductFeignService;
import com.gulimall.gulimallorder.feign.WmsFeignService;
import com.gulimall.gulimallorder.interceptor.LoginUserInterceptor;
import com.gulimall.gulimallorder.service.OrderItemService;
import com.gulimall.gulimallorder.to.OrderCreateTo;
import com.gulimall.gulimallorder.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.gulimallorder.dao.OrderDao;
import com.gulimall.gulimallorder.entity.OrderEntity;
import com.gulimall.gulimallorder.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OrderItemService orderItemService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取订单确认页面信息
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo=new OrderConfirmVo();
        MemberEntityVo memberEntityVo = LoginUserInterceptor.threadLocal.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //多线程下无法拿到之前请求的数据,从而导致拦截器报空指针
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询所有收获地址列表
            List<MemberAddressVo> address = memberFeignService.getAddress(memberEntityVo.getId());
            confirmVo.setAddress(address);
        }, threadPoolExecutor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //多线程下无法拿到之前请求的数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询购物车服务中的购物项
            List<OrderItemVo> orderItemVos = cartFeignService.getcurrentUserCartItems();
            confirmVo.setItems(orderItemVos);
        }, threadPoolExecutor).thenRunAsync(()->{
            //批量查询订单的有货无货状态
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> {
                Long skuId = item.getSkuId();
                return skuId;
            }).collect(Collectors.toList());
            //远程调用库存服务
            R skusHasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVo> data = skusHasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if(data!=null&&data.size()>0){
                Map<Long, Boolean> booleanMap =
                        data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(booleanMap);
            }
        });

        //查询用户积分
        confirmVo.setIntegration(memberEntityVo.getIntegration());
        //其他数据自动计算
        CompletableFuture.allOf(addressFuture,cartFuture).get();
        //TODO 放重令牌
        String uuid = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(uuid);
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberEntityVo.getId(),uuid,30, TimeUnit.MINUTES);
        return confirmVo;
    }

    /**
     * 下单
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        //下单，创建订单，校验令牌，校验价格，锁库存
        SubmitOrderResponseVo responseVo=new SubmitOrderResponseVo();
        MemberEntityVo memberEntityVo = LoginUserInterceptor.threadLocal.get();
        String token = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId());
        //校验令牌，使用lua脚本保证判断令牌和删除令牌的原子性
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        List<String> list = Arrays.asList(stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId()));
        Long execute = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), list, vo.getOrderToken());
        if(execute==0){
            //校验令牌失败
            responseVo.setCode(1);
            return responseVo;
        }
        //令牌验证成功 创建订单，校验令牌，校验价格，锁库存
        OrderCreateTo orderCreateTo = orderCreateTo(vo);
        //验价
        BigDecimal priceByVo = vo.getPayPrice();//页面提交的价格
        BigDecimal priceByCount = orderCreateTo.getOrder().getPayAmount();//后台计算的价格
        if(!(Math.abs(priceByCount.subtract(priceByVo).doubleValue())<0.01)){
            //价格发生变化提醒用户
            responseVo.setCode(2);
            return responseVo;
        }
        //保存订单
        saveOrder(orderCreateTo);
        //锁定库存 有异常就回滚订单数据

        return null;
    }

    /**
     * 保存订单
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        //保存订单
        this.save(order);
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        //保存订单项
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 创建订单
     * @return
     */
    private OrderCreateTo orderCreateTo(OrderSubmitVo vo){
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1，生成订单号
        String timeId = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = buildOrder(vo,timeId);
        orderCreateTo.setOrder(orderEntity);
        //获取所有的订单项信息
        List<OrderItemEntity> orderItemEntities = bulidOrderItems(timeId);
        if(orderItemEntities==null){

        }
        orderCreateTo.setOrderItems(orderItemEntities);

        //,价格相关
        computePrice(orderEntity,orderItemEntities);

        return orderCreateTo;
    }

    /**
     *   //验价,价格相关
     * @param orderEntity 订单
     * @param orderItemEntities 订单项
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal coupon = new BigDecimal("0");
        Integer Integration = 0;
        Integer growth=0;
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            growth=growth+orderItemEntity.getGiftGrowth();
            Integration=Integration+orderItemEntity.getGiftIntegration();
            coupon=coupon.add(orderItemEntity.getCouponAmount());
            integration=integration.add(orderItemEntity.getIntegrationAmount());
            promotion=promotion.add(orderItemEntity.getPromotionAmount());
            total=total.add(orderItemEntity.getRealAmount());
        }
        //总金额
        orderEntity.setTotalAmount(total);
        //应付金额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //每个优惠的总价格
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
        //设置积分,成长值信息
        orderEntity.setIntegration(Integration);
        orderEntity.setGrowth(growth);
    }

    /**
     * 创建订单
     * @param vo
     * @return
     */
    private OrderEntity buildOrder(OrderSubmitVo vo ,String orderId) {
        MemberEntityVo memberEntityVo = LoginUserInterceptor.threadLocal.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderId);
        //获取收获地址信息
        R fare = wmsFeignService.getFare(vo.getAddrId());
        FareVo data = fare.getData(new TypeReference<FareVo>() {
        });
        if(data==null){

        }
        //设置会员的id
        orderEntity.setMemberId(memberEntityVo.getId());
        //设置运费信息
        orderEntity.setFreightAmount(data.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(data.getMemberAddressVo().getCity());
        orderEntity.setReceiverDetailAddress(data.getMemberAddressVo().getDetailAddress());
        orderEntity.setReceiverName(data.getMemberAddressVo().getName());
        orderEntity.setReceiverPhone(data.getMemberAddressVo().getPhone());
        orderEntity.setReceiverPostCode(data.getMemberAddressVo().getPostCode());
        orderEntity.setReceiverProvince(data.getMemberAddressVo().getProvince());
        orderEntity.setReceiverRegion(data.getMemberAddressVo().getRegion());

        //设置订单状态相关信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //设置订单的自动确认时间
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setDeleteStatus(0);//未删除
        return orderEntity;
    }

    //将购物车中的数据转换为订单项
    private List<OrderItemEntity> bulidOrderItems(String orderId) {
        //最后确定购物车中的价格，一旦确定即使商品调价，也是使用这个价格
        List<OrderItemVo> orderItemVos = cartFeignService.getcurrentUserCartItems();
        if(orderItemVos!=null&&orderItemVos.size()>0){
            List<OrderItemEntity> itemEntities = orderItemVos.stream().map(item -> {
                //将购物车中的数据转换为订单项
                OrderItemEntity orderItemEntity=buildOrerItem(item,orderId);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 创建某个订单项
     * @param item
     * @param orderId
     * @return
     */
    private OrderItemEntity buildOrerItem(OrderItemVo item, String orderId) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //订单信息：订单号
        orderItemEntity.setOrderSn(orderId);
        //spu
        R r = productFeignService.getSpuInfoBySkuId(item.getSkuId());
        SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        //sku
        orderItemEntity.setSkuId(item.getSkuId());
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        List<String> skuAttr = item.getSkuAttr();
        String attrs = StringUtils.collectionToDelimitedString(skuAttr, ";");
        orderItemEntity.setSkuAttrsVals(attrs);
        orderItemEntity.setSkuQuantity(item.getCount());
        //积分信息 买的数量越多积分越多
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
        //优惠信息（不做）
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //计算该订单项的真实价格
        BigDecimal realPrice = orderItemEntity.getSkuPrice()
                .multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()))
                .subtract(new BigDecimal(orderItemEntity.getPromotionAmount().toString()))
                .subtract(new BigDecimal(orderItemEntity.getCouponAmount().toString()))
                .subtract(new BigDecimal(orderItemEntity.getIntegrationAmount().toString()));
        orderItemEntity.setRealAmount(realPrice);
        return orderItemEntity;
    }

}